package cn.itsource.controller.app;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.itsource.constants.RConst;
import cn.itsource.core.CosTemplate;
import cn.itsource.result.JSONResult;
import cn.itsource.utils.AssertUtil;
import com.qcloud.cos.model.ObjectMetadata;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/app/cos")
public class CosController {

    @Autowired
    private CosTemplate cosTemplate;

    @RequestMapping("/upload")
    @SaIgnore
    public JSONResult fileUpload(@RequestParam("file") MultipartFile file){
        AssertUtil.isFalse(file.isEmpty(),"文件为空");
        try {
            String filename = file.getOriginalFilename();
            String suffix = filename.substring(filename.lastIndexOf(RConst.Str.DOT));
            String fileUrl = cosTemplate.uploadFile(file.getInputStream(), new ObjectMetadata(), suffix);
            return JSONResult.success(fileUrl);
        } catch (IOException e) {
            log.info(e.getMessage());
            throw new RuntimeException(e);
        }
    }

}
